#include <stdio.h>
#include <stdlib.h> // exit
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <iostream>
#include <errno.h>
#include "cli.h"
#include "syscore.h"
#include "apis.h"

using namespace cli;
using namespace std;

int main(int argc,char **argv)
{
    printf("Start Cli Server for testing.\n");
    key_t key = ftok("/tmp", MSGQ_FTOK_ID ^ 0xff);
    if (key == (key_t)-1) 
    {
        printf("ftok(%d) failed, %s\n", MSGQ_FTOK_ID ^ 0xff, strerror(errno));
        exit(EXIT_FAILURE);
    }
    int rxQueueId_m = msgget(key, IPC_CREAT);
    cout << "rxQueueId:" << rxQueueId_m << ", key:" << key <<endl;
    
    key = ftok("/tmp", MSGQ_FTOK_ID);
    if (key == (key_t)-1) 
    {
        printf("ftok(%d) failed, %s\n", MSGQ_FTOK_ID, strerror(errno));
        exit(EXIT_FAILURE);
    }
    int txQueueId_m = msgget(key, IPC_CREAT);
    cout << "txQueueId:" << txQueueId_m << ", key:" << key <<endl;

    char msgBuf[MAX_MSG_SIZE];
    while(1)
    {
        cout << "wait for message..." << endl;
        int msgLen = msgrcv(rxQueueId_m, msgBuf, MAX_MSG_SIZE, 0, 0);
        if(msgLen==-1)
        {
            printf("Can NOT recv message from rxQueue~~~\n");
            int err = errno;
            if(err <= 0 && err != EINTR)
            {
                printf("Error %s\n",strerror(err));
            }
            sleep(1);
            continue;
        }

        cout << "received message length" << msgLen << endl;
        
        int ret_value = msgsnd(txQueueId_m, msgBuf, msgLen ,0);  
        if ( ret_value < 0 ) {  
            printf("msgsnd() write msg failed,errno=%d[%s]\n",errno,strerror(errno));  
            return false;  
        }
        memset(msgBuf, 0, msgLen);
        
    }

    exit(EXIT_SUCCESS);
}

